<template lang="pug">
mt-card
  .ignore-entry-type
    ElTree(class="filter-tree"
      :data="treeData"
      :filter-node-method="filterNode"
      v-loading="loadingMap['treeData']"
      ref="tree"
      node-key="id"
      :accordion="false"
      :highlight-current="true"
      :expand-on-click-node="false"
      :props="{ label: 'name' }"
      :default-expanded-keys="defaultExpandedKeys"
      )
      template(#default="{ node, data }")
        span(class="custom-tree-node",@click="nodeClick(data, node)")
          span {{ node.label }}
          span.custom-tree-node-icon
            Icon(name="Delete",v-if="isNotDelete.indexOf(data.level) == -1",@click.stop="deleteNode(data)",title="删除")
            Icon(name="EditPen",v-if="isNotDelete.indexOf(data.level) == -1",@click.stop="update(data)",title="修改")
            Icon(name="Plus",v-if="isNotAdd.indexOf(data.level) == -1",@click.stop="append(data)",title="新增")
edit(v-model="editingModel",:selectItem="editingItem",@handleQuery="handleQuery")
</template>
<script setup lang="ts">
import { Icon, useNotify, ElMessageBox, ElTree } from "@scmt/common-components";
const tree = ref<null | InstanceType<typeof ElTree>>(null);
import { useRequest } from "@scmt/common-hooks";
import { useApi } from "@scmt/core-api";
import type { EntryTypeEntity } from "@scmt/api-pacs-entry-type";
import edit from "./components/edit.vue";
const $api = useApi();
const model = ref<EntryTypeEntity>($api.pacs.entryType.$$createEntity({}));
const editingItem = ref<EntryTypeEntity>();

const editingModel = ref(false);

const $notify = useNotify();
const defaultExpandedKeys = ref<any[]>([]);
const currentNodeKey = ref("");
const isNotDelete = ref([0, 1]);
const isNotAdd = ref([3]);
//定义事件
const emit = defineEmits(["nodeClick"]);
//树状数据
const treeData = ref<any[]>([]);
const { request, data, loadingMap } = useRequest({
  treeData: () => {
    model.value = $api.pacs.entryType.$$createEntity({});
    return $api.pacs.entryType.queryTree({ isGetAll: 0 }).then((res) => {
      const appData = data.treeData ?? res;
      let resData: any[] = [];
      if (appData && appData.length > 0) {
        resData = appData;
        if (resData && resData.length > 0) {
          defaultExpandedKeys.value.push(resData[0].id);
          if (resData[0].children) {
            model.value = resData[0].children[0];
            model.value.parentId = model.value?.id;
            emit("nodeClick", model.value);
            nextTick(() => {
              currentNodeKey.value = resData[0].children[0].id;
              tree.value?.setCurrentKey(currentNodeKey.value);
            });
          }
        }
      }
      treeData.value = resData;
    });
  },
  destroy: (ids: string) => {
    return $api.pacs.entryType.destroy(ids).then(() => {
      $notify.success("删除成功");
      request("treeData");
    });
  },
});

//页面加载完执行
onMounted(() => {
  request("treeData");
});

const filterNode = (value: any, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/**
 * 节点点击事件
 */
const nodeClick = (value: any, node: any) => {
  if (value && node && data) {
    model.value = value;
    if (model.value.id) {
      model.value.parentId = model.value?.id;
    } else {
      model.value.parentId = multiFilterTree(value, node);
    }
    emit("nodeClick", model.value);
  }
};

//递归查找树结构 code 为空的数据
const multiFilterTree = (value: any, node: any) => {
  let filteredNodes = "";
  if (node && value) {
    if (node.data.code) {
      filteredNodes = node.data.id;
      return filteredNodes;
    }
    if (node.parent) {
      filteredNodes = multiFilterTree(value, node.parent);
    }
  }
  return filteredNodes;
};

const handleQuery = () => {
  request("treeData");
};
/**
 * 新增事件
 */
const append = (data: any) => {
  model.value = data;
  if (data) {
    editingItem.value = $api.pacs.entryType.$$createEntity({
      parentName: data.name,
      parentId: data?.id,
      officeId: data.officeId,
      officeName: data.officeName,
      level: data.level + 1,
    });
    editingModel.value = true;
  }
};
/**
 * 删除事件
 */
const deleteNode = (data: any) => {
  if (data) {
    ElMessageBox.confirm("您是否要删除当前数据?", "确认删除", {
      confirmButtonText: "确认",
      type: "warning",
      center: true,
    })
      .then(() => {
        request("destroy", data.id);
      })
      .catch(() => {});
  }
};

/**
 * 编辑事件
 */
const update = (data: any) => {
  editingItem.value = Object.assign({ parentName: data.name }, data);
  editingModel.value = true;
};
</script>

<style lang="less" scoped>
.ignore-entry-type {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;

  :deep(.el-tree-node) {
    .is-current > .el-tree-node__content {
      background: #1c7bef;
      color: #fff;

      .mt-icon {
        color: #fff;
      }
    }

    .el-tree-node__content {
      height: 40px;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding-right: 8px;

    span:first-child {
      white-space: normal;
      line-height: 12px;
      font-size: 12px;
      font-weight: 700;
    }

    &-icon {
      display: flex;

      .mt-icon {
        color: #1c7bef;
        padding: 0px var(--mt-padding-small);
      }
    }
  }
}
</style>
